package com.kfm.spring.advice;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component("jdbcAdvice")
@Aspect
public class JDBCAdvice {

    @Pointcut("execution(* com.kfm.spring.service.*.get*(..))")
    public void pt(){}


    @Before("pt()")
    public void beginTransaction(JoinPoint joinPoint) {
        System.out.println("开启事务");
    }

    @AfterReturning("pt()")
    public void commit(JoinPoint joinPoint) {
        System.out.println("提交事务");
    }

    @AfterThrowing("pt()")
    public void rollback() {
        System.out.println("回滚事务");
    }

    @After("pt()")
    public void close() {
        System.out.println("释放资源");
    }

    public Object around(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            // 开启事务
            beginTransaction(joinPoint);
            // 执行代理方法
            result = joinPoint.proceed(joinPoint.getArgs());
            // 提交事务
            commit(joinPoint);
        } catch (Throwable e) {
            // 回滚事务
            rollback();
            throw new RuntimeException(e);
        }finally {
            // 释放资源
            close();
        }
        return result;
    }
}
